<template>
  <div class="btn-container">
    <template v-for="(item, index) in firstOptions">
      <a :key="index" class="btn-item" @click="btnClick('firstOptions', index)">{{ item.name }}</a>
    </template>
    <div v-if="lastOptions.length > 0" class="btn-item">
      <el-popover
        :ref="`popover-${scope.$index}`"
        placement="bottom"
        width="100"
        trigger="click"
      >
        <div class="btn-list">
          <template v-for="(item, index) in lastOptions">
            <div :key="index" class="popover-item" @click="btnClick('lastOptions', index,scope.$index)">{{ item.name }}</div>
          </template>
        </div>
        <a v-if="lastOptions.length > 0" slot="reference">更多 <i class="el-icon-arrow-down" /></a>
      </el-popover>
    </div>
  </div>
</template>

<script>
import { checkPermission, getPermissionArray } from '@/utils/index'
import store from '@/store'

export default {
  name: 'BtnSetting',
  props: {
    options: {
      type: Array,
      default: null
    },
    row: {
      type: Object,
      default: null
    },
    scope: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      handledOptions: [],
      firstOptions: [],
      lastOptions: []
    }
  },
  watch: {
    row(val) {
      this.handleCondition()
    }
  },
  mounted() {
    this.handleCondition()
  },
  methods: {
    handleCondition(val) {
      const resultRole = getPermissionArray(store.getters && store.getters.roles)
      let first = []
      const last = []
      const handledOptions = this.options.filter(v => (!v.v_if || (v.v_if && v.v_if(this.row))) &&
      (!v.permission || (v.permission && checkPermission(v.permission, resultRole))))
      if (handledOptions.length <= 4) {
        first = [...handledOptions]
      } else {
        handledOptions.forEach((v, i) => {
          if (i <= 2) {
            first.push(v)
          } else {
            last.push(v)
          }
        })
      }
      this.firstOptions = first
      this.lastOptions = last
    },
    btnClick(optionsStr, index, s) {
      this[optionsStr][index].handler(this.row)
      if (optionsStr === 'lastOptions') {
        this.$refs[`popover-${s}`].doClose()
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .btn-container {
    .btn-item {
      color: #D6000F;
      padding-left: 10px;
      display: inline-block;
      &:first-child {
        padding-left: 0;
      }
    }
  }
  .btn-list {
    cursor: pointer;
    .popover-item {
      text-align: center;
      line-height: 30px;
    }
  }
</style>
